package com.mybook.app.service;

import com.github.pagehelper.PageInfo;
import com.mybook.app.core.BaseResponse;
import com.mybook.app.core.UserContext;
import com.mybook.app.core.WebPageInfo;
import com.mybook.app.dto.BookInfoAndUserInfoDto;
import com.mybook.app.exception.DataIsEmptyException;
import com.mybook.app.mapper.BookInfoMapper;
import com.mybook.app.mapper.TransInfoMapper;
import com.mybook.app.mapper.UserInfoMapper;
import com.mybook.app.model.BookInfo;
import com.mybook.app.model.TransInfo;
import com.mybook.app.model.UserInfo;
import com.mybook.app.request.BookInfoRequest;
import com.mybook.app.request.ShareListRequest;
import com.mybook.app.response.ShareBook;
import com.mybook.app.response.ShareDetail;
import com.mybook.app.response.ShareKeeper;
import com.mybook.app.response.ShareList;
import com.mybook.app.utils.IdUtils;
import com.mybook.app.utils.LatLngUtils;
import com.mybook.app.utils.Logger;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by zjutsw on 2017/11/1.
 */
@Service
public class ShareBookService {

    @Autowired
    private BookInfoMapper bookInfoMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private TransInfoMapper transInfoMapper;
    @Autowired
    private UserService userService;

    /**
     * 分享图书
     *
     * @param bookInfoRequest
     * @return
     */
    public void shareBook(BookInfoRequest bookInfoRequest) {
        //
        BookInfo bookInfo = new BookInfo();
        BeanUtils.copyProperties(bookInfoRequest, bookInfo);
        //设置ID
        UserInfo userInfo = userInfoMapper.findUserInfoById(UserContext.getCurrentuserId().get());
        //城市代码city(6位）+YYYYMMDDHHMISSsss（17位）+hostid（5位）+4位随机数
        String id = IdUtils.getId(userInfo.getCity());
        bookInfo.setId(id);
        bookInfo.setcTime(new Date());
        bookInfo.setuTime(new Date());
        bookInfo.setBorrows(0);
        bookInfo.setCuId(UserContext.getCurrentuserId().get());
        bookInfo.setOuId(UserContext.getCurrentuserId().get());
        bookInfo.setStar(0);
        bookInfo.setBorrowStatus(1);//默认为分享
        bookInfo.setBorrowStatus(1);// 默认可借阅
        int row = bookInfoMapper.insertSelective(bookInfo);
        Logger.info(this, "分享图书是否成功： " + row);
    }

    /**
     * 分享列表
     *
     * @param shareListRequest
     * @return
     */
    public BaseResponse<ShareList> shareList(ShareListRequest shareListRequest) {

        //获取用户id
        shareListRequest.setOuId(UserContext.getCurrentuserId().get());
        List<BookInfo> bookInfos = bookInfoMapper.findBookInfoByOcId(shareListRequest);
        if (CollectionUtils.isEmpty(bookInfos)) {
            Logger.info(this, "我的分享为空");
            throw new DataIsEmptyException();
        }
        PageInfo<BookInfo> pageInfo = new PageInfo<>(bookInfos);

        List<ShareList> shareLists = bookInfos.stream().map(bookInfo -> {
            ShareList shareList = new ShareList();
            BeanUtils.copyProperties(bookInfo, shareList);
            shareList.setbId(bookInfo.getId());
            shareList.setBorrowTimes(bookInfo.getBorrows());
            //查询每一本数据收益
            BigDecimal bigDecimal = transInfoMapper.findTransInfoIncomeByBid(bookInfo.getId());
            shareList.setIncome(null == bigDecimal ? BigDecimal.ZERO : bigDecimal);
            // 查询书籍状态
            List<String> statuss = transInfoMapper.findTransInfoStatusByBid(bookInfo.getId());
            if (CollectionUtils.isNotEmpty(statuss)) {
                // 设置书籍状态
                shareList.setStatus(statuss.get(0));
            } else {
                shareList.setStatus("0");
            }
            return shareList;
        }).collect(Collectors.toList());

        //数据转化
        BaseResponse baseResponse = new BaseResponse(shareLists);
        baseResponse.setPageInfo(new WebPageInfo());
        BeanUtils.copyProperties(pageInfo, baseResponse.getPageInfo());
        return baseResponse;
    }

    /**
     * 分享详情
     * <p>
     * 通过bId 查询书籍信息和当前持有人信息
     *
     * @param bId
     */
    public ShareDetail shareDetail(String bId) {
        //查询书本信息
        BookInfoAndUserInfoDto bookInfoAndUserInfoDto = bookInfoMapper.findBookInfoByIdWithUserInfo(bId);
        if (null == bookInfoAndUserInfoDto) {
            Logger.info(this, "查询数据为空");
            throw new DataIsEmptyException();
        }
        // 数据转换
        // 书籍
        ShareDetail shareDetail = new ShareDetail();
        ShareBook shareBook = new ShareBook();
        BeanUtils.copyProperties(bookInfoAndUserInfoDto, shareBook);
        shareBook.setbId(bookInfoAndUserInfoDto.getId());
        shareBook.setBorrowTimes(bookInfoAndUserInfoDto.getBorrows());
        shareDetail.setShareBook(shareBook);

        //持有者
        ShareKeeper shareKeeper = new ShareKeeper();
        BeanUtils.copyProperties(bookInfoAndUserInfoDto.getCuUserInfo(), shareKeeper);
        // 设置距离
        shareKeeper.setDistance(LatLngUtils.getDistance(userService.getCoor(), bookInfoAndUserInfoDto.getCuUserInfo().getCoor()));

        //设置借阅信息
        List<TransInfo> transInfos = transInfoMapper.findTransInfoByBid(bId);
        if (CollectionUtils.isNotEmpty(transInfos)) {
            TransInfo transInfo = transInfos.get(0);
            shareKeeper.setCost(transInfo.getCost());
            shareKeeper.setBeginTime(transInfo.getiTime());
            shareKeeper.setEndTime(transInfo.geteTime());
        }
        shareDetail.setShareKeeper(shareKeeper);

        return shareDetail;
    }

    public void shareBack(String bId) {
        Logger.debug(this, "收回当前书本操作");
        Integer row = bookInfoMapper.updateBookInfoFlagByBid(bId);
        Logger.info(this, "是否操作成功： " + row);

    }
}
